<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use App\Libs\Util;
use App\Libs\WeChat\Transfer\WxTransfer;
use iBrand\Component\Order\Models\Order;
use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\EC\Open\Backend\Store\Repositories\GoodsRepository;
use iBrand\EC\Open\Server\Transformers\OrderTransformer;
use iBrand\EC\Open\Server\Transformers\GoodsTransformer;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    protected $orderRepository;

    public function __construct(OrderRepository $orderRepository,GoodsRepository $goodsRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->goodsRepository = $goodsRepository;
    }


    public function orderList(){
        $user_id = request()->user()->id;
        $page = request('page',0);
        $status = request('status',0);
        $where =[];
        if($status){
            $where['status'] = $status;
        }
        $order_info = DB::table('ibrand_order')->where(['user_id'=>$user_id,'is_valid'=>1])->where($where)->orderby('created_at',"DESC")->skip($page*10)->take(10)->get(['id','order_no','status','count','real_freight','type','channel','total'])->toArray();
        if ($order_info){
            foreach ($order_info as &$v){
                if($v->status==1){
                    $status_name = '待付款';
                }elseif ($v->status==2){
                    $status_name = '待发货';
                }elseif ($v->status==3){
                    $status_name = '待收货';
                }elseif ($v->status==4){
                    $status_name = '待评价';
                }elseif ($v->status==5){
                    $status_name = '已完成';
                }elseif ($v->status==6){
                    $status_name = '已取消';
                }elseif ($v->status==7){
                    $status_name = '已退款';
                }
                $v->status_name = $status_name;
                $order_item_info = DB::table('ibrand_order_item')->leftjoin('ibrand_goods_product','ibrand_goods_product.sku','=','ibrand_order_item.sku')->where(['order_id'=>$v->id])->get(['item_id','item_name','quantity','spec_ids','sell_price','ibrand_goods_product.sku'])->toArray();

                foreach ($order_item_info as &$item){
                    //type==3是拼团订单 查询拼团价
                    if($v->type==1){
                        $activity_goods = DB::table('activity_goods')->where(['goods_id'=>$item->item_id,'sku'=>$item->sku])->orderBy('created_at','DESC')->first();
                        $item->activity_price = $activity_goods->activity_price;
                        $arrs = explode('_',$v->channel);
                        $item->at_id = $arrs[3];
                    }
                    $goods_info = DB::table('ibrand_goods')->where(['id'=>$item->item_id])->first();
                    $item->img = $goods_info->img;
                    $spec_ids = json_decode(($item->spec_ids),true);
                    //var_dump($spec_ids);
                    $spec_info = DB::table('ibrand_goods_spec_value')->whereIn('id',$spec_ids)->get(['name'])->toArray();
                    if($spec_info){
                        $spec_name_arr = array_column($spec_info,'name');
                        $spec_name = implode(' ',$spec_name_arr);
                        $item->spec_name = $spec_name;
                    }
                    //查询该商品是否评价
                    $com_res = DB::table('ibrand_order_comment')->where(['order_id'=>$v->id,'item_id'=>$item->item_id])->first();
                    $item->comment_status = $com_res?1:0;
                    $v->spec_info[] = $item;
                }
                $v->total = sprintf('%.2f', ($v->total/100));
                $v->real_freight = sprintf('%.2f', ($v->real_freight/100));
            }
        }
        return $this->success($order_info);
    }


    public function editOrder(){
        $user = request()->user();
        $user_id = $user->id;
        $openid = $user->openid;
        $order_id = request('order_id');
        $type = request('type');
        //1.取消2.收货3.删除
        if(!$order_id){
            $this->failed('缺少订单信息');
        }
        $where = ['order_no'=>$order_id,'user_id'=>$user_id];
        $order = DB::table('ibrand_order')->where($where)->first();
        if($order){
            switch ($type){
                case 1 :
                    $order_status = 6;
                    if($order->status != 1 && $order->status != 2){
                        return $this->success('订单状态有误！暂时不能取消');
                    }
                    //如果有优惠券退还优惠券
                    if($order->coupon_code){
                        DB::table('ibrand_discount_coupon')->where(['code'=>$order->coupon_code])->update(['used_at'=>NULL]);
                    }
                    if($order->status == 2){
                        $order_status = 7;
                        //退款
                        $wx = new WxTransfer();
                        $refund = [];
                        $refund['order_no']=$order->order_no;
                        $refund['total_fee']=$order->total;
                        $res = $wx->refund($refund);
                        if($res){
                            //退还积分
                            $member_info = get_member($openid);
                            if($member_info){
                                $before_bonus = $member_info->bonus;
                                $change_bonus = ceil($order->total/100);
                                $after_bonus = $before_bonus-$change_bonus;
                                $status = 1;
                                $type = 2;
                                //调用微信的接口加积分
                                $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                if($result['errcode']==0){
                                    add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                }else{
                                    savelog('wx_bonus', '订单已经支付过'.$order->order_number.'错误：'.$result->errmsg);
                                }
                            }
                            savelog('refund_order_success', (json_encode($order)));
                        }else{
                            savelog('refund_order_fail', (json_encode($order)));
                        }
                    }
                    //修改订单的状态
                    DB::table('ibrand_order')->where(['order_no'=>$order->order_no])->update(['status'=>$order_status]);
                    break;
                case 2 :
                    DB::table('ibrand_order')->where($where)->update(['status'=>4]);
                    //判断是否有分销 如果有则计算
                    if($order->agent_id){
                        frozen_money($order->agent_id,$order->id,$order->distribution_total,2);
                        account_money($order->agent_id,$order->id,$order->distribution_total,1);
                    }
                    break;
                case 3 :
                    DB::table('ibrand_order')->where($where)->update(['is_valid'=>0]);
                    break;
            }
        }
        return $this->success('操作成功');
    }

    public function editOrders(){
        //$user = request()->user();
        $order_id = request('order_no');
        $user_id = request('user_id');
        $openid = request('openid');
        //$user_id = 394;
        //$openid = 'oyybT5M7pbuD1Ydkupw0zel3U79E';


        $type = 1;
        //1.取消2.收货3.删除
        if(!$order_id){
            $this->failed('缺少订单信息');
        }
        $where = ['order_no'=>$order_id,'user_id'=>$user_id];
        $order = DB::table('ibrand_order')->where($where)->first();
        if($order){
            switch ($type){
                case 1 :
                    $order_status = 6;
                    if($order->status != 1 && $order->status != 2){
                        return $this->success('订单状态有误！暂时不能取消');
                    }
                    //如果有优惠券退还优惠券
                    if($order->coupon_code){
                        DB::table('ibrand_discount_coupon')->where(['code'=>$order->coupon_code])->update(['used_at'=>NULL]);
                    }
                    if($order->status == 2){
                        $order_status = 7;
                        //退款
                        $wx = new WxTransfer();
                        $refund = [];
                        $refund['order_no']=$order->order_no;
                        $refund['total_fee']=$order->total;
                        $res = $wx->refund($refund);
                        if($res){
                            //退还积分
                            $member_info = get_member($openid);
                            if($member_info){
                                $before_bonus = $member_info->bonus;
                                $change_bonus = ceil($order->total/100);
                                $after_bonus = $before_bonus-$change_bonus;
                                $status = 1;
                                $type = 2;
                                //调用微信的接口加积分
                                $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                if($result['errcode']==0){
                                    add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                }else{
                                    savelog('wx_bonus', '订单已经支付过'.$order->order_number.'错误：'.$result->errmsg);
                                }
                            }
                            savelog('refund_order_success', (json_encode($order)));
                        }else{
                            savelog('refund_order_fail', (json_encode($order)));
                        }
                        //修改订单的状态
                        DB::table('ibrand_order')->where(['order_no'=>$order->order_no])->update(['status'=>$order_status]);
                    }

                    break;
                case 2 :
                    DB::table('ibrand_order')->where($where)->update(['status'=>4]);
                    //判断是否有分销 如果有则计算
                    if($order->agent_id){
                        frozen_money($order->agent_id,$order->id,$order->distribution_total,2);
                        account_money($order->agent_id,$order->id,$order->distribution_total,1);
                    }
                    break;
                case 3 :
                    DB::table('ibrand_order')->where($where)->update(['is_valid'=>0]);
                    break;
            }
        }
        return $this->success('操作成功');
    }

    /**
     * 申请提现
     */
    public function apply(){
        $user = request()->user();
        $user_id = $user->id;
        $openid = $user->openid;
        //$money = request('money');
        //查询账户的余额
        $account = DB::table('user_account')->where(['user_id'=>$user_id])->first();
        if(!$account){
            return $this->failed('信息错误');
        }
        if($account->total_money <= 0){
            return $this->failed('可提现金额不足！');
        }
        $res = DB::table('settle_order')->where(['user_id'=>$user_id,'status'=>0])->first();
        if($res){
            return $this->failed('还有未处理的结算申请，请耐心等待！');
        }
        $order_no = date( 'YmdHis',time() ).rand(1111,9999);
        $res = DB::table('settle_order')->insert(['settlement_amount'=>$account->total_money,'order_no'=>$order_no,'user_id'=>$user_id,'apply_time'=>date('Y-m-d H:i:s',time()),'money'=>$account->total_money,'status'=>0]);
        return $this->success('操作成功');
    }


    public function getOrders()
    {
        //$orderConditions['channel'] = \request('channel') ? \request('channel') : 'ec';

        if (request('order_no')) {
            $orderConditions['order_no'] = request('order_no');
        }

        if (request('status')) {
            $orderConditions['status'] = request('status');
        } else {
            $orderConditions['status'] = ['status', '<>', 0];
            $orderConditions['status2'] = ['status', '<>', 9];
        }

        $orderConditions['user_id'] = request()->user()->id;

        $itemConditions = [];

        $limit = request('limit') ? request('limit') : 10;

        if ($criteria = request('criteria')) {
            $itemConditions['order_no'] = ['order_no', 'like', '%'.$criteria.'%'];
            $itemConditions['item_name'] = ['item_name', 'like', '%'.$criteria.'%'];
            $itemConditions['item_id'] = ['item_id', 'like', '%'.$criteria.'%'];

            $order = $this->orderRepository->getOrdersByCriteria($orderConditions, $itemConditions, $limit);
        } else {
            $order = $this->orderRepository->getOrdersByConditions($orderConditions, $itemConditions,
                $limit, ['items', 'shippings', 'adjustments', 'items.product', 'items.product.goods']);
        }

        $transformer = request('transformer') ? request('transformer') : 'list';

        return $this->response()->paginator($order, new OrderTransformer($transformer));
    }




    public function getOrderDetails($orderno)
    {
        $user = request()->user();

        $order = $this->orderRepository->getOrderByNo($orderno);

        if ($user->cant('update', $order)) {
            return $this->failed('无权操作');
        }

        return $this->response()->item($order, new OrderTransformer());
    }
}
